package org.dromara.websocket.message;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.dromara.websocket.connection.Connection;
import org.dromara.websocket.connection.ConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by       PokerFace
 * Create Date      2020-06-15.
 * Email:
 * Version          1.0.0
 * <p>
 * Description:
 */
public class TextWebSocketFrameInboundHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    public static final Logger logger = LoggerFactory.getLogger(TextWebSocketFrameInboundHandler.class);


    private MessageListener messageListener;
    private ConnectionManager connectionManager;


    public TextWebSocketFrameInboundHandler(MessageListener messageListener, ConnectionManager connectionManager) {
        this.messageListener = messageListener;
        this.connectionManager = connectionManager;
    }

    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        Connection connection = connectionManager.getConnection(ctx);
        if (connection == null) {
            logger.warn("connection is null. drop message!!!");
            return;
        }
        if (messageListener != null) {
            // 回调方法
            try{
                messageListener.onMessage(connection, msg.text());
            }catch (Exception e){
                logger.error("Handle Message Error", e);
            }
        }
    }




    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        Channel incoming = ctx.channel();
        logger.error("Client:"+incoming.remoteAddress()+"异常");
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}
